﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using TemplateWeb.Models;
using TemplateWeb.Models.ViewModels;
using TemplateWeb.Helpers;

namespace TemplateWeb.Controllers
{

    [HandleError]
    public class AccountController : BaseController
    {

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    return RedirectToAction("Index", "Admin");
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult LogOn2(FormCollection forms)
        {
            string username = forms.GetValues("username")[0];
            string password = forms.GetValues("password")[0];
            bool remember = true;
            if (MembershipService.ValidateUser(username, password))
            {
                FormsService.SignIn(username, remember);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }

            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_REGISTER
            };
            return View(CreateViewModel(data));
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("Index", "Home");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        public ActionResult Register()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_REGISTER
            };
            return View(CreateViewModel(data));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Register(FormCollection forms/*, bool captchaValid*/)
        {
            string errorText = "";
            var NguoiDungInfo = new AddNguoiDungViewModel
            {
                Info = new NguoiDungInfo
                {
                    BaseInfo = new NguoiDungBaseInfo
                    {
                        UserName = forms.GetValues("username")[0],
                        Password = forms.GetValues("password")[0],
                        Email = forms.GetValues("email")[0],
                        Role = "customer"
                    },
                    ExtraInfo = new NguoiDung
                    {
                        HoTen = forms.GetValues("hoten")[0],
                        SoDienThoai = forms.GetValues("sodienthoai")[0],
                        DiaChi = forms.GetValues("diachi")[0]
                    }
                }
            };
            var result = _repNguoiDung.Insert(NguoiDungInfo, ref errorText);
            if (result)
            {
                FormsService.SignIn(forms.GetValues("username")[0], false /* createPersistentCookie */);
                return RedirectToAction("Index", "Home");
            }

            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_REGISTER
            };
            return View(CreateViewModel(data));
        }

        public ActionResult ThongTinNguoiDung(string username)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_DETAILOF_NGUOIDUNG,
                UserName = username
            };
            return View("ThongTinNguoiDung", CreateViewModel(data));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult CapNhatThongTinTaiKhoan(FormCollection forms/*, bool captchaValid*/)
        {
            var NguoiDungInfo = new EditNguoiDungViewModel
            {
                ID = Guid.Parse(forms.GetValues("NguoiDung_ID")[0])
            };
            var user = Membership.GetUser(NguoiDungInfo.ID);
            user.Email = forms.GetValues("NguoiDung_Email")[0];
            Membership.UpdateUser(user);

            var extrainfo = _repNguoiDung.SelectByID(NguoiDungInfo.ID);
            extrainfo.HoTen = forms.GetValues("NguoiDung_HoTen")[0];
            var result = _repNguoiDung.Save();

            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_DETAILOF_NGUOIDUNG,
                UserName = forms.GetValues("NguoiDung_UserName")[0],
                InfoText = result ? "Đã cập nhật thông tin" : "Thông tin chưa được cập nhật"
            };
            return View("ThongTinNguoiDung", CreateViewModel(data));
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        public ActionResult ResetPassword()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ResetPassword(FormCollection forms)
        {
            var username = forms.GetValues("NguoiDung_UserName")[0];
            if (!Membership.EnablePasswordReset)
            {
                FormsAuthentication.RedirectToLoginPage();
            }

            MembershipUser user = Membership.GetUser(username, false);
            var newPassword = user.ResetPassword();
            if (newPassword != null)
            {
                var email = RenderPartialViewToString("ResetPasswordTemplate");
                email = email.Replace("[Password]", newPassword);
                if (SendingMail("Reset Password in " + WebConfiguration.SiteName, email, user.Email))
                    return RedirectToAction("PasswordResetSuccess");
                return RedirectToAction("PasswordResetFailed");
            }
            return RedirectToAction("PasswordResetFailed");
        }

        public ActionResult PasswordResetSuccess()
        {
            return View();
        }

        public ActionResult PasswordResetFailed()
        {
            return View();
        }

    }
}
